package sy.controller;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import sy.model.Taskrecord;
import sy.model.Texchange;
import sy.pageModel.DataGrid;
import sy.pageModel.Json;
import sy.pageModel.Mexchange;
import sy.pageModel.Mtaskrecord;
import sy.pageModel.PageHelper;
import sy.pageModel.SessionInfo;
import sy.pageModel.User;
import sy.service.ExchangeServiceI;
import sy.service.ExchangetypeServiceI;
import sy.service.ResourceServiceI;
import sy.service.RoleServiceI;
import sy.service.TaskRecordServiceI;
import sy.service.UserServiceI;
import sy.util.ConfigUtil;
import sy.util.IpUtil;
import cn.jpush.api.utils.ParseXml;
import cn.jpush.api.utils.PayHttpClinet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 兑换控制器
 * 
 * @author 甘涛
 * 
 */
@Controller
@RequestMapping("/texchangeController")
public class TexchangeController extends BaseController {
	@Autowired
	private  ExchangeServiceI exchangeService;
	@Autowired
	private UserServiceI userService;
	
	@Autowired
	private ExchangetypeServiceI changetype;
	
	@Autowired
	private UserController usercontrol;
	
	
	
	//未审核
	@ResponseBody
	@RequestMapping("/addexchange")
	public String addexchange(Mexchange exchange, HttpSession session,HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		JSONObject jsobj = new JSONObject();
		SessionInfo sessionInfo = (SessionInfo)session.getAttribute(ConfigUtil.getSessionInfoName());
		if(sessionInfo == null){
			jsobj.put("status", -1);
			jsobj.put("msg", "登录超时");
		}else{
		try {
			if(exchangeService.getCheckCount(sessionInfo.getId(), exchange.getType()) == 0){
				if(userService.get(sessionInfo.getId()).getUnchangedscore() >=exchange.getScore()){
					exchange.setUserid(sessionInfo.getId());
				    exchange.setChangestatus("0");
					exchangeService.add(exchange);
					usercontrol.updatetotalscore(sessionInfo.getId(), exchange.getScore(), 2);//先扣掉积分
					jsobj.put("status", "1");
					jsobj.put("msg", "sccuess");
				}else{
					jsobj.put("status", "1");
					jsobj.put("msg", "您当前积分不够!");
				}
			}else{
				jsobj.put("status", "1");
				jsobj.put("msg", "等待审核处理。。");
			}
		} catch (Exception e) {
			e.printStackTrace();
			jsobj.put("status", "0");
			jsobj.put("msg","申请失败");
		}
		}
		return jsobj.toJSONString();
	}
	
	/**
	 * 审核功能
	 * 
	 * @param q
	 * @param ph
	 * @return
	 */
	@RequestMapping("/checkexchange")
	@ResponseBody
	public Json changeexchange(String id,String type,String typenum,Integer score,String sessionid) {
		 String reulst = "";
		 Json j = new Json();
		 try {
			if("1".equals(type)){ 	  //Q币
				if(score == 10000){
					reulst=this.addqq(1, typenum,score,sessionid);
				}else if(score == 98000){
					reulst=this.addqq(10, typenum,score,sessionid);
				}else if(score == 195000){
					reulst=this.addqq(20, typenum,score,sessionid);
				}else if(score == 290000){
					reulst=this.addqq(30, typenum,score,sessionid);
				}else if(score == 480000){
					reulst=this.addqq(50,typenum,score,sessionid);
				}
			}else if("2".equals(type)){ //qq业务
				
			}else if("3".equals(type)){ //支付宝
				if(score == 1050000){
					reulst=this.addzfb(10,typenum,score,sessionid);
				}else if(score == 2050000){
					reulst=this.addzfb(20,typenum,score,sessionid);
				}else if(score == 3050000){
					reulst=this.addzfb(30,typenum,score,sessionid);
				}else if(score == 5050000){
					reulst=this.addzfb(50,typenum,score,sessionid);
				}else if(score == 10000000){
					reulst=this.addzfb(100,typenum,score,sessionid);
				}else if(score == 50000000){
					reulst=this.addzfb(500,typenum,score,sessionid);
				}
			}else if("4".equals(type)){ //话费
				if(score == 2000000){
					reulst=this.addhponemoney("20",typenum,score,sessionid);//20
				}else if(score == 3000000){
					reulst=this.addhponemoney("30",typenum,score,sessionid);//30
				}else if(score == 5050000){
					reulst=this.addhponemoney("50",typenum,score,sessionid);//50
				}else if(score == 1000000){
					reulst=this.addhponemoney("100",typenum,score,sessionid);//100
				}else if(score == 2000000){
					reulst=this.addhponemoney("200",typenum,score,sessionid);//100
				}
			}else if("5".equals(type)){ //财付通
				
			}else if("6".equals(type)){ //苹果
				
			}else{
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			reulst="error";
		}
		if("success".equals(reulst)){
			 j.setSuccess(true);
	         j.setMsg("审核成功！");
	         exchangeService.updatestatu(id, "1");//兑换成功的标识
		}else{
			 j.setSuccess(false);
	         j.setMsg("审核失败！");
	         exchangeService.updatestatu(id, "3");//兑换失败的表示
		}
		return j;
	}
	/**
	 * 查询公共兑换记录接口
	 * 
	 * @param q
	 * @param ph
	 * @return
	 */
	@RequestMapping("/publicexchange")
	@ResponseBody
	public String getnewexchange(HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		JSONObject jsobj = new JSONObject();
		int i = 0;
		try {
			List<Texchange>  exchange = exchangeService.getNewExchange();
			if(exchange.size()!= 0){
				List<Texchange>  exchangetrue = new ArrayList<Texchange>();
				for(Texchange change : exchange){
					if(i >= 50){
						break;
					}
					Texchange obj = new Texchange();
					String contont = changetype.getexchange(change.getType()).getTypecontent();
					String unit    = changetype.getexchange(change.getType()).getUnit();
					contont=contont+" "+change.getGoods()+unit;
					obj.setExchangecontent(contont);
					obj.setExchangetime(change.getExchangetime());
					obj.setNickname((userService.get(change.getUserid())).getName());
					obj.setDisplaytime(change.getDisplaytime());
					obj.setChangestatus(change.getChangestatus());
					exchangetrue.add(obj);
					i++;
				 }
				jsobj.put("status", "1");
				jsobj.put("msg", exchangetrue);
			}else{
				jsobj.put("status", "1");
				jsobj.put("msg", exchange);
			}
		} catch (Exception e) {
			e.printStackTrace();
			jsobj.put("status", "0");
			jsobj.put("msg", "异常信息");
		}
		return jsobj.toJSONString();
	}
	//查看个人兑换记录
	@RequestMapping("/personexchange")
	@ResponseBody
	public String getnewexchange(HttpSession session,HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		JSONObject jsobj = new JSONObject();
		SessionInfo sessionInfo = (SessionInfo)session.getAttribute(ConfigUtil.getSessionInfoName());
		if(sessionInfo == null){
			jsobj.put("status", -1);
			jsobj.put("msg", "登录超时");
		}else{
		try {
			List<Texchange>  exchange = exchangeService.getexchange(sessionInfo.getId());
			List<Texchange>  exchangetrue = new ArrayList<Texchange>();
			if(exchange.size()!=0){
				for(Texchange change : exchange){
					Texchange obj = new Texchange();
					String contont = changetype.getexchange(change.getType()).getTypecontent();
					String unit    = changetype.getexchange(change.getType()).getUnit();
					contont=contont+" "+change.getGoods()+unit;
					obj.setExchangecontent(contont);
					obj.setExchangetime(change.getExchangetime());
					obj.setNickname((userService.get(change.getUserid())).getName());
					obj.setDisplaytime(change.getDisplaytime());
					obj.setChangestatus(change.getChangestatus());
					exchangetrue.add(obj);
				 }
				jsobj.put("status", "1");
				jsobj.put("msg", exchangetrue);
			}else{
				jsobj.put("status", "1");
				jsobj.put("msg", exchangetrue);
			}
		} catch (Exception e) {
			e.printStackTrace();
			jsobj.put("status", "0");
			jsobj.put("msg", "异常信息");
		}
		}
		return jsobj.toJSONString();
	}
	
	/**
	 * 跳转到兑换记录页面
	 * 
	 * @return
	 */
	@RequestMapping("/exchange")
	public String exchange() {
		return "/exchange/index";
	}
	
	/**
	 * 跳转到兑换记录页面
	 * 
	 * @return
	 */
	@RequestMapping("/mangereuslt")
	public String mangereuslt() {
		return "/exchange/indexreulst";
	}
	
	/**
	 * 获取用兑换数据
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("/dataGrid")
	@ResponseBody
	public DataGrid dataGrid(Mexchange change, PageHelper ph) {
		return exchangeService.dataGrid(change, ph);
	}
	
	/**
	 * 兑换类型管理
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("/mangetype")
	public String  mangetype() {
		return "/exchange/exchangetype/index";
	}
	
	/**
	 * 查询
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping("/payfor")
	@ResponseBody
	public String  payfor(HttpServletResponse response) {
		response.setCharacterEncoding("utf-8");
		PayHttpClinet clinet = new PayHttpClinet();
		JSONObject jsobj = new JSONObject();
		try {
			jsobj.put("statu", "1");
			jsobj.put("msg", clinet.payfor());
			System.out.println(clinet.payfor());
			return  jsobj.toJSONString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "error";
	}
	
	
	//交电话费
	public String  addhponemoney(String number,String phonenuber,Integer score,String sessionid) {
		PayHttpClinet clinet = new PayHttpClinet();
		String result = "false";
		try {
			ParseXml doc = new ParseXml();
	        if( "1".equals(doc.xmlElements(clinet.insertphone(number, phonenuber)))){//判断返回结果
	        	result ="success";
	        }else{
	        	usercontrol.updatetotalscore(sessionid, score, 1);
	        }
		} catch (Exception e) {
			e.printStackTrace();
			result ="false";
		}
		return result;
	}
	//加支付宝
	public String  addzfb(int number,String phonenuber,Integer score,String sessionid) {
		PayHttpClinet clinet = new PayHttpClinet();
		String result = "false";
		try {
			ParseXml doc = new ParseXml();
	        if("1".equals(doc.xmlElements(clinet.insterpaypal(number, phonenuber)))){//判断返回结果
	        	result ="success";
	        }else{
	        	usercontrol.updatetotalscore(sessionid, score, 1);
	        }
		 
		} catch (Exception e) {
			result ="false";
			e.printStackTrace();
		}
		return result;
	}
	
	//加QQ业务
	public String  addqq(int number,String qq,Integer score,String sessionid) {
		PayHttpClinet clinet = new PayHttpClinet();
		String result = "false";
		try {
			ParseXml doc = new ParseXml();
	        if( "1".equals(doc.xmlElements(clinet.insterqb(number, qq)))){ //判断返回结果
	        	result ="success";
	        }else{
	        	usercontrol.updatetotalscore(sessionid, score, 1);
	        }
			 
		} catch (Exception e) {
			result ="false";
			e.printStackTrace();
		}
		return result;
	}
	
	  /**
     * 批量删除任务
     *
     * @param ids
     *            ('0','1','2')
     * @return
     */
    @RequestMapping("/batchDelete")
    @ResponseBody
    public Json batchDelete(String ids) {
        Json j = new Json();
        if (ids != null && ids.length() > 0) {
            for (String id : ids.split(",")) {
                if (id != null) {
                    this.delete(id);
                }
            }
        }
        j.setMsg("批量删除成功！");
        j.setSuccess(true);
        return j;
    }
    
    /**
     * 批量审核
     *
     * @param ids
     *            ('0','1','2')
     * @return
     */
    @RequestMapping("/batchCheck")
    @ResponseBody
    public Json batchCheck(String ids) {
        Json j = new Json();
        if (ids != null && ids.length() > 0) {
            for (String id : ids.split(",")) {
                if (id != null) {
                	Texchange exchange = exchangeService.getTexchangedetial(id);
                	if("1".equals(exchange.getType())){
                		this.changeexchange(id, exchange.getType(), exchange.getQq(), exchange.getScore(), exchange.getUserid());
                	}else if("2".equals(exchange.getType())){
                		
                	}else if("3".equals(exchange.getType())){
                		this.changeexchange(id, exchange.getType(), exchange.getAlipay(), exchange.getScore(), exchange.getUserid());
                	}else if("4".equals(exchange.getType())){
                		this.changeexchange(id, exchange.getType(), exchange.getCellPhone(), exchange.getScore(), exchange.getUserid());
                	}else if("5".equals(exchange.getType())){
                		
                	}else if("6".equals(exchange.getType())){
                		
                	}else{
                		
                	}
                }
            }
        }
        j.setMsg("批量审核完成！");
        j.setSuccess(true);
        return j;
    }
    
    public Json delete(String id) {
    	   
        Json j = new Json();
        if (id != null) { 
        	exchangeService.delete(id);
        }
        j.setMsg("删除成功！");
        j.setSuccess(true);
        return j;
    }
}
